package com.example.iot.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.iot.R;

import java.util.ArrayList;
import java.util.List;

public class sendActivity extends AppCompatActivity {
    static String[] permissions={
            "android.permission.SEND_SMS",
            "android.permission.READ_PHONE_STATE"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);
        List<String> list=new ArrayList<>();
        list.clear();
        for(int i=0;i<permissions.length;i++){
            if(ContextCompat.checkSelfPermission(this,permissions[i])!= PackageManager.PERMISSION_GRANTED){
                list.add(permissions[i]);
            }
        }
        if(list.isEmpty()){
            fun();
        }else{
            String[] needP=list.toArray(new String[list.size()]);
            ActivityCompat.requestPermissions(this,needP,1);
        }
    }
    void fun(){
        findViewById(R.id.bt_send_send).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                EditText et1=findViewById(R.id.et_sned_phone);
                EditText et2=findViewById(R.id.et_send_content);
                SmsManager smsManager=SmsManager.getDefault();
                List<String> list=smsManager.divideMessage(et2.getText().toString());
                for(String sms:list){
                    smsManager.sendTextMessage(et1.getText().toString(),null,sms,null,null);
                }
            }
        });

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch(requestCode){
            case 1:
                for(int i=0;i<grantResults.length;i++){
                    if(grantResults[i]!=PackageManager.PERMISSION_GRANTED){
                        Toast.makeText(this, "权限不足，功能无法全部实现!", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
                fun();
        }
    }

}